<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
        name="viewport">
  <meta content="ie=edge" http-equiv="X-UA-Compatible">
  <title>状态保存与恢复</title>
  <style></style>
</head>
<body>
<!--canvas-->
<canvas height="500" id="canvas" width="500"></canvas>
</body>
<script>
  // 1.状态保存与恢复
  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');

  ctx.fillStyle = 'red';
  ctx.fillRect(0, 0, 100, 100);
  ctx.save();

  ctx.fillStyle = 'blue';
  ctx.fillRect(100, 100, 100, 100);
  ctx.save();

  ctx.fillStyle = 'green';
  ctx.fillRect(200, 200, 100, 100);

  ctx.restore();
  ctx.fillRect(300, 300, 100, 100);
  
  ctx.restore();
  ctx.fillRect(400, 400, 100, 100);
</script>
</html>